package com.ay.utils;

import com.ay.entity.ApprovalRecord;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import org.springframework.core.io.ClassPathResource;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

public class PdfTemplateUtil {
    
    private static final Font TITLE_FONT = new Font(Font.FontFamily.HELVETICA, 18, Font.BOLD);
    private static final Font SUBTITLE_FONT = new Font(Font.FontFamily.HELVETICA, 14, Font.BOLD);
    private static final Font NORMAL_FONT = new Font(Font.FontFamily.HELVETICA, 12, Font.NORMAL);
    private static final Font SMALL_FONT = new Font(Font.FontFamily.HELVETICA, 10, Font.NORMAL);
    
    /**
     * 根据模板生成PDF
     * @param templatePath 模板路径
     * @param data 数据
     * @param approvalRecords 审批记录
     * @return PDF字节数组
     */
    public static byte[] generatePdf(String templatePath, Map<String, Object> data, List<ApprovalRecord> approvalRecords) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        
        // 创建PDF文档
        Document document = new Document(PageSize.A4);
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        document.open();
        
        // 添加标题
        addTitle(document, "审批文档");
        
        // 添加基本信息
        addBasicInfo(document, data);
        
        // 添加审批历史
        addApprovalHistory(document, approvalRecords);
        
        // 添加签名区域
        addSignatureArea(document);
        
        document.close();
        return baos.toByteArray();
    }
    
    /**
     * 添加标题
     */
    private static void addTitle(Document document, String title) throws DocumentException {
        Paragraph titleParagraph = new Paragraph(title, TITLE_FONT);
        titleParagraph.setAlignment(Element.ALIGN_CENTER);
        titleParagraph.setSpacingAfter(20f);
        document.add(titleParagraph);
    }
    
    /**
     * 添加基本信息
     */
    private static void addBasicInfo(Document document, Map<String, Object> data) throws DocumentException {
        // 添加基本信息表格
        PdfPTable table = new PdfPTable(2);
        table.setWidthPercentage(100);
        table.setSpacingBefore(10f);
        table.setSpacingAfter(10f);
        
        // 设置列宽
        float[] columnWidths = {1f, 2f};
        table.setWidths(columnWidths);
        
        // 添加数据
        for (Map.Entry<String, Object> entry : data.entrySet()) {
            table.addCell(new PdfPCell(new Phrase(entry.getKey(), NORMAL_FONT)));
            table.addCell(new PdfPCell(new Phrase(String.valueOf(entry.getValue()), NORMAL_FONT)));
        }
        
        document.add(table);
    }
    
    /**
     * 添加审批历史
     */
    private static void addApprovalHistory(Document document, List<ApprovalRecord> records) throws DocumentException {
        // 添加审批历史标题
        Paragraph historyTitle = new Paragraph("审批历史", SUBTITLE_FONT);
        historyTitle.setSpacingBefore(20f);
        historyTitle.setSpacingAfter(10f);
        document.add(historyTitle);
        
        // 创建审批历史表格
        PdfPTable table = new PdfPTable(5);
        table.setWidthPercentage(100);
        table.setSpacingBefore(10f);
        table.setSpacingAfter(10f);
        
        // 设置列宽
        float[] columnWidths = {1f, 1f, 1f, 2f, 1.5f};
        table.setWidths(columnWidths);
        
        // 添加表头
        String[] headers = {"审批人", "角色", "状态", "意见", "时间"};
        for (String header : headers) {
            PdfPCell cell = new PdfPCell(new Phrase(header, NORMAL_FONT));
            cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);
        }
        
        // 添加审批记录
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        for (ApprovalRecord record : records) {
            table.addCell(new PdfPCell(new Phrase(record.getApproverName(), SMALL_FONT)));
            table.addCell(new PdfPCell(new Phrase(record.getApproverRole(), SMALL_FONT)));
            table.addCell(new PdfPCell(new Phrase(record.getApprovalStatus(), SMALL_FONT)));
            table.addCell(new PdfPCell(new Phrase(record.getApprovalComment(), SMALL_FONT)));
            table.addCell(new PdfPCell(new Phrase(record.getApprovalTime().format(formatter), SMALL_FONT)));
        }
        
        document.add(table);
    }
    
    /**
     * 添加签名区域
     */
    private static void addSignatureArea(Document document) throws DocumentException {
        // 添加签名区域标题
        Paragraph signatureTitle = new Paragraph("签名区域", SUBTITLE_FONT);
        signatureTitle.setSpacingBefore(20f);
        signatureTitle.setSpacingAfter(10f);
        document.add(signatureTitle);
        
        // 创建签名表格
        PdfPTable table = new PdfPTable(2);
        table.setWidthPercentage(100);
        table.setSpacingBefore(10f);
        table.setSpacingAfter(10f);
        
        // 设置列宽
        float[] columnWidths = {1f, 1f};
        table.setWidths(columnWidths);
        
        // 添加签名行
        for (int i = 0; i < 3; i++) {
            PdfPCell cell1 = new PdfPCell(new Phrase("签名：", NORMAL_FONT));
            cell1.setBorder(Rectangle.NO_BORDER);
            cell1.setPaddingBottom(20f);
            table.addCell(cell1);
            
            PdfPCell cell2 = new PdfPCell(new Phrase("日期：", NORMAL_FONT));
            cell2.setBorder(Rectangle.NO_BORDER);
            cell2.setPaddingBottom(20f);
            table.addCell(cell2);
        }
        
        document.add(table);
    }
    
    /**
     * 保存PDF文件
     */
    public static void savePdf(byte[] pdfBytes, String outputPath) throws IOException {
        try (FileOutputStream fos = new FileOutputStream(outputPath)) {
            fos.write(pdfBytes);
        }
    }
} 